package com.bigdata.service.impl;

import com.bigdata.dao.NWQualityRankMapper;
import com.bigdata.entity.NWQualityRank;
import com.bigdata.entity.NWQualityRankVO;
import com.bigdata.service.NWQualityRankService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class NWQualityRankServiceImpl implements NWQualityRankService {

    private final NWQualityRankMapper nwQualityRankMapper;

    @Override
    public NWQualityRankVO getNetworkQualityRank(Long startTime, Long endTime, String networkQuality) {
        String qualityField = getQualityField(networkQuality);

        try {
            // 获取所有运营商的平均数据
            List<NWQualityRank> allData = nwQualityRankMapper.getAllOperatorsData(startTime, endTime, qualityField);

            // 获取各运营商数据
            List<List<NWQualityRank>> operatorData = new ArrayList<>();
            for (String operator : Arrays.asList("CMCC", "CUCC", "CTCC")) {
                List<NWQualityRank> data = nwQualityRankMapper.getOperatorData(startTime, endTime, operator, qualityField);
                operatorData.add(data);
            }

            // 构建返回数据
            NWQualityRankVO result = new NWQualityRankVO();

            // 设置图例
            result.setLegends(Arrays.asList("ALL", "CMCC", "CUCC", "CTCC"));

            // 设置X轴数据(省份)
            result.setXAxisData(allData.stream()
                    .map(NWQualityRank::getProvince)
                    .collect(Collectors.toList()));

            // 设置系列数据
            List<List<Double>> seriesData = new ArrayList<>();

            // 添加ALL数据
            seriesData.add(allData.stream()
                    .map(NWQualityRank::getSpeed)
                    .collect(Collectors.toList()));

            // 添加各运营商数据
            for (List<NWQualityRank> data : operatorData) {
                seriesData.add(data.stream()
                        .map(NWQualityRank::getSpeed)
                        .collect(Collectors.toList()));
            }

            result.setSeriesData(seriesData);
            return result;

        } catch (Exception e) {
            log.error("获取网络质量排名数据失败", e);
            throw new RuntimeException("获取网络质量排名数据失败", e);
        }
    }

    private String getQualityField(String networkQuality) {
        switch (networkQuality) {
            case "上行速率":
                return "ULSPEED";
            case "延迟":
                return "LATENCY";
            default:
                return "DLSPEED";
        }
    }
}